//
//  GetStateViewController.m
//  uniquelove
//
//  Created by ibokan on 14-12-10.
//  Copyright (c) 2014年 ibokan. All rights reserved.
//

#define TextFont [UIFont systemFontOfSize:17]


#import "GetStateViewController.h"
#import "AFNetworking.h"
#import "WriteStateViewController.h"
#import "StateModel.h"
#import "StateFrame.h"
#import "StateTableViewCell.h"

@interface GetStateViewController ()
@property (strong, nonatomic) NSMutableArray *states;

@property (assign, nonatomic) BOOL isLoading;
@property (assign, nonatomic) BOOL isForNewData;

@end



/*
 result =     (
 {
 state =             {
 address = "";
 content = "\U640f\U51fb\U82cd\U7a79\U4e0a\Uff0c\U7ff1\U7fd4\U5929\U5730\U95f4";
 date = "2014-12-10 10:30:10";
 fromUid = 2056483717;                自己的1956859800
 id = 5722;
 image = "";
 imagecount = 0;
 latitude = "";
 longitude = "";
 };
 },
 */

@implementation GetStateViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(BOOL)prefersStatusBarHidden{   //隐藏状态栏
    return YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.isLoading = NO;
    self.isForNewData = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.states = [[NSMutableArray alloc]initWithCapacity:100];
    
    [self refreshTheData];

}

-(void)refreshTheData{
    
    NSLog(@"refreshTheData");
    static int a = 10;
    if (self.isForNewData) {
        a += 5;
        self.isForNewData = NO;
    }
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    NSString *token = (NSString *)[[NSUserDefaults standardUserDefaults]objectForKey:@"accessToken"];
    NSString *userID = (NSString *)[[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
	NSDictionary *dic = @{@"access_token": token,@"uid":userID,@"size":[NSString stringWithFormat:@"%d",a]};
    
    //获取状态内容
    [manager GET:@"http://lovemyqq.sinaapp.com/getState.php" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [self.states removeAllObjects];
        
        NSDictionary *dic = responseObject;
        NSArray *array = dic[@"result"];
        
       
        
        for (NSDictionary * dict in array) {
            StateModel *stateModel = [StateModel new];
            
            stateModel.text = dict[@"state"][@"content"];
            
            stateModel.time = dict[@"state"][@"date"];
            NSString *fromUid = dict[@"state"][@"fromUid"];
            
            if ([fromUid isEqualToString:@"1956859800"]) {
                stateModel.type = StateTypeMe;
            }else{
                stateModel.type = StateTypeOther;
            }
            
            StateFrame *sf = [StateFrame new];
            sf.stateModel = stateModel;
            [self.states addObject:sf];
        }
        self.isLoading = NO;
        [self.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.states.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    StateTableViewCell *cell = [StateTableViewCell cellWithTableView:tableView];
    
    cell.stateFrame = self.states[indexPath.row];
    
    return cell;
}

#pragma mark - 代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StateFrame *stateFrame = self.states[indexPath.row];
    return stateFrame.cellHeight;
}

//下拉刷新
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    // 假设偏移表格高度的20%进行刷新
    if (!_isLoading) { // 判断是否处于刷新状态，刷新中就不执行
        
        // 取内容的高度：
        //    如果内容高度大于UITableView高度，就取TableView高度
        //    如果内容高度小于UITableView高度，就取内容的实际高度
        float height = scrollView.contentSize.height > _tableView.frame.size.height ?_tableView.frame.size.height : scrollView.contentSize.height;
        if ((height - scrollView.contentSize.height + scrollView.contentOffset.y) / height > 0.2) {
            // 调用上拉刷新方法
            NSLog(@"shang la shua xin");
            _isLoading = YES;
            self.isForNewData = YES;
            [self performSelector:@selector(refreshTheData) withObject:nil afterDelay:2];
           
        }
        
        if (- scrollView.contentOffset.y / _tableView.frame.size.height > 0.2) {
            // 调用下拉刷新方法
            _isLoading = YES;
            NSLog(@"xia la shua xin ");
//            self.isForNewData = YES;
            [self performSelector:@selector(refreshTheData) withObject:nil afterDelay:2];

        }
        
    }
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    WriteStateViewController *writeState = segue.destinationViewController;
    writeState.getState = self;
}


@end
